//
//  TableViewController.m
//  Mobile-contracts-ios
//
//  Created by TuoHongwei on 14-5-25.
//  Copyright (c) 2014年 zsyApp. All rights reserved.
//

#import "TableViewController.h"
#import "ContactReadTool.h"
#import "ContactModel.h"
#import <AddressBookUI/AddressBookUI.h>
@interface TableViewController ()

@end

@implementation TableViewController
@synthesize PersonAry,SectionDict,SectionMutableAry;
- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title=@"通讯录";
    [self loadTable];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return [[SectionDict allKeys] count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    NSArray * sectionInfoAry = [self.SectionDict objectForKey:[self.SectionMutableAry objectAtIndex:section]];
    return [sectionInfoAry count];
}

-(void) loadTable{
    ContactReadTool * readTool = [ContactReadTool getContactReadTool];
    [readTool reReadContact];
    self.SectionDict = [NSMutableDictionary dictionary];
    self.SectionMutableAry = [NSMutableArray array];
    self.PersonAry = readTool.PersonAry;
    self.PersonAry = (NSMutableArray *)[self.PersonAry sortedArrayUsingComparator:^NSComparisonResult(ContactModel *obj1, ContactModel *obj2) {
        return [obj1.PersonNameFirstLetter compare:obj2.PersonNameFirstLetter];
    }];
    
    for (ContactModel * contactModel in PersonAry) {
        NSMutableArray* section = [SectionDict objectForKey:contactModel.PersonNameFirstLetter];
        if (!section) {
            section = [NSMutableArray array];
            [SectionDict setObject:section forKey:contactModel.PersonNameFirstLetter];
            [self.SectionMutableAry addObject:contactModel.PersonNameFirstLetter];
        }
        [section addObject:contactModel];
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString*CellIdentifier=@"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        cell.textLabel.textColor=[UIColor blueColor];
        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    }
    
    NSArray * sectionOfCellAry  = [self.SectionDict objectForKey:[self.SectionMutableAry objectAtIndex:[indexPath section]]];
    ContactModel  * model = [sectionOfCellAry objectAtIndex:[indexPath row]];
    cell.textLabel.text = model.PersonName;
    if ([model.PersonImageData bytes] != 0 ) {
        //        dispatch_queue_t queue = dispatch_get_global_queue(
        //                                                           DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        //        dispatch_async(queue, ^{
        cell.imageView.image = [UIImage imageWithData:model.PersonImageData];
        //        });
    }else{
        cell.imageView.image = [UIImage imageNamed:@"aaa.png"];
    }
    return cell;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [self.SectionMutableAry objectAtIndex:section];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ABAddressBookRef addressBook = ABAddressBookCreate();
    NSMutableArray* perAry=[self.SectionDict objectForKey:[self.SectionMutableAry objectAtIndex:indexPath.section]];
    ABRecordRef person = ABAddressBookGetPersonWithRecordID(addressBook, (ABRecordID)[[perAry objectAtIndex:indexPath.row] PersonID]);
    
    if (person != NULL) {
        ABPersonViewController * personViewController = [[ABPersonViewController alloc]init];
        [personViewController setDisplayedPerson:person];
        personViewController.allowsActions = YES;
        personViewController.allowsEditing =YES;
        personViewController.personViewDelegate=self;
        [self.navigationController pushViewController:personViewController animated:YES];
    }
    
}

- (BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
    //NSLog(@"this is ");
    return  YES;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
